package com.ruoyi.article.common;

import com.ruoyi.article.domain.Article;
import com.ruoyi.article.service.IArticleService;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author qinbo
 * @version 1.0
 * @description: TODO
 * @date 2025/6/1 14:53
 */
@Component
@EnableScheduling
public class RedisToDatabaseSyncTask {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IArticleService articleService;

    @Scheduled(fixedRate = 1000) // 每隔一分钟执行一次
    public void syncArticleViewsToDatabase() {
        // 获取Redis中"article:"前缀的所有键
        Set<Long> keys = redisCache.getCacheSet("article:");
        System.out.println("开始处理缓存中的点击量");

        for (Long key : keys) {
            // 获取Redis中存储的点击量
            Integer viewCount = redisCache.getCacheObject("article:click-count:" + key);

            // 调用service层的方法更新数据库
            Article article = articleService.selectArticleByArticleId(key);
            if (article != null) {
                article.setClickCount(article.getClickCount()+viewCount);
                articleService.updateArticle(article);

                // 更新成功后，可以考虑删除Redis中的数据，或者保留以便下次更新时使用
                 redisCache.deleteObject("article:click-count:" + key);
            }
        }
        redisCache.deleteObject( "article:");
        System.out.println("处理缓存中的点击量完成");
    }
}
